import React, { useEffect, useState }  from "react"
import { Tag } from 'antd';
import {Link} from 'react-router-dom'
import { connect } from 'react-redux'
import { addHistoryRouter,filterHistoryRouter } from 'redux/action'
import { withRouter } from "react-router-dom";


function HistoryTabs(props) {  
   const {tabList} = props
   const [tabIndex,setIndex] = useState(0)

  //  获取当前高亮的tab下标
   useEffect(()=>{
     const data = props.location.pathname.split('/').filter(i=>i)
     //  存在子集
     if(data[2]){
      setIndex(tabList.findIndex(i=>{
        return i.url.indexOf('?')===-1?i.url===data[1] + '/' + data[2]:i.url.slice(0,i.url.indexOf('?'))===data[1] + '/' + data[2]
      }))
     } else {
      setIndex(tabList.findIndex(i=>i.url===data[1]))
     }
   },[props, props.location.pathname, tabList])
   
  //  清除已经删除的
  const log = (index) =>{
    props.filterRouter(index)
  }


return <div className="head-tabs">
  {
    tabList.map((i,index)=>{
      return <Tag onClose={()=>log(index)}  color={tabIndex===index?'success':''}  key={i.url}  closable={tabIndex!==index}>
      <Link to={"/view/"+ i.url } >{i.menuName}</Link>
    </Tag>
    })
  }
</div>
}
// 获取redux数据
const mapStateToProps = (state) => {
  return {
    tabList: state.tabList,
    collapsed:state.collapsed
  }
}
// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    filterRouter:(index)=> dispatch(filterHistoryRouter(index))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(HistoryTabs))   